﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using WinServiceFileListener.Consts;

namespace WinServiceFileListener.Helpers
{
    public class LogHelper
    {
        // 获取当前日志文件的路径
        public static void WriteLog(object obj)
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{DateTime.Now:yyyy-MM-dd} Log.txt");
            string output = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {obj}";
            using (StreamWriter writer = new StreamWriter(path, true))
            {
                writer.WriteLine(output);
                writer.Flush();
            }
            Console.WriteLine(output);
            // 异步删除超过天数的日志文件
            Task.Run(() => DeleteLogs());
        }
        

        private static void DeleteLogs()
        {
            // 获取日志文件目录
            string logDirectory = AppDomain.CurrentDomain.BaseDirectory;

            // 获取所有日志文件
            string[] logFiles = Directory.GetFiles(logDirectory, "* Log.txt");

            foreach (string logFile in logFiles)
            {
                // 获取文件的创建时间
                DateTime creationTime = File.GetCreationTime(logFile);

                // 如果文件超过3天，则删除
                if ((DateTime.Now - creationTime).TotalDays > IniConst.LogSaveDay)
                {
                    File.Delete(logFile);
                }
            }
        }
    }
}
